from django import forms
from .models import Goods, Inbound, Outbound, Stock, Inventory, WageRule


class GoodsForm(forms.ModelForm):
    class Meta:
        model = Goods
        fields = ['name', 'specification', 'unit', 'shelf_life', 'min_stock', 'max_stock']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'specification': forms.TextInput(attrs={'class': 'form-control'}),
            'unit': forms.TextInput(attrs={'class': 'form-control'}),
            'shelf_life': forms.NumberInput(attrs={'class': 'form-control'}),
            'min_stock': forms.NumberInput(attrs={'class': 'form-control'}),
            'max_stock': forms.NumberInput(attrs={'class': 'form-control'}),
        }
        labels = {
            'name': '商品名称',
            'specification': '规格',
            'unit': '单位',
            'shelf_life': '保质期（天）',
            'min_stock': '最小库存',
            'max_stock': '最大库存',
        }
        help_texts = {
            'shelf_life': '请输入保质期天数，留空表示无保质期',
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(GoodsForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        goods = super(GoodsForm, self).save(commit=False)
        if self.user:
            goods.creator = self.user
        if commit:
            goods.save()
        return goods


class InboundForm(forms.ModelForm):
    class Meta:
        model = Inbound
        fields = ['goods', 'quantity', 'supplier', 'purchase_order']
        widgets = {
            'goods': forms.Select(attrs={'class': 'form-control'}),
            'quantity': forms.NumberInput(attrs={'class': 'form-control'}),
            'supplier': forms.TextInput(attrs={'class': 'form-control'}),
            'purchase_order': forms.TextInput(attrs={'class': 'form-control'}),
        }
        labels = {
            'goods': '商品',
            'quantity': '数量',
            'supplier': '供应商',
            'purchase_order': '采购单号',
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(InboundForm, self).__init__(*args, **kwargs)
        # 只显示可用的商品
        self.fields['goods'].queryset = Goods.objects.all()

    def save(self, commit=True):
        inbound = super(InboundForm, self).save(commit=False)
        if self.user:
            inbound.operator = self.user
        if commit:
            inbound.save()
            # 更新库存
            stock, created = Stock.objects.get_or_create(
                goods=inbound.goods,
                location='默认货位',  # 简化处理，实际项目中应该让用户选择货位
                batch_number=inbound.purchase_order or '默认批次',
                defaults={'quantity': inbound.quantity}
            )
            if not created:
                stock.quantity += inbound.quantity
                stock.save()
        return inbound


class OutboundForm(forms.ModelForm):
    class Meta:
        model = Outbound
        fields = ['goods', 'quantity', 'customer']
        widgets = {
            'goods': forms.Select(attrs={'class': 'form-control'}),
            'quantity': forms.NumberInput(attrs={'class': 'form-control'}),
            'customer': forms.TextInput(attrs={'class': 'form-control'}),
        }
        labels = {
            'goods': '商品',
            'quantity': '数量',
            'customer': '客户',
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(OutboundForm, self).__init__(*args, **kwargs)
        # 只显示有库存的商品
        self.fields['goods'].queryset = Goods.objects.filter(stock__quantity__gt=0).distinct()

    def save(self, commit=True):
        outbound = super(OutboundForm, self).save(commit=False)
        if self.user:
            outbound.operator = self.user
            outbound.approver = self.user  # 简化处理，实际项目中应该有审批流程
        if commit:
            # 检查库存是否足够
            try:
                stock = Stock.objects.filter(goods=outbound.goods).first()
                if stock and stock.quantity >= outbound.quantity:
                    outbound.save()
                    # 更新库存
                    stock.quantity -= outbound.quantity
                    stock.save()
                else:
                    raise forms.ValidationError("库存不足")
            except Stock.DoesNotExist:
                raise forms.ValidationError("该商品无库存记录")
        return outbound


class InventoryForm(forms.ModelForm):
    class Meta:
        model = Inventory
        fields = ['goods', 'location', 'batch_number', 'actual_quantity', 'note']
        widgets = {
            'goods': forms.Select(attrs={'class': 'form-control'}),
            'location': forms.TextInput(attrs={'class': 'form-control'}),
            'batch_number': forms.TextInput(attrs={'class': 'form-control'}),
            'actual_quantity': forms.NumberInput(attrs={'class': 'form-control'}),
            'note': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
        }
        labels = {
            'goods': '商品',
            'location': '货位编号',
            'batch_number': '批次号',
            'actual_quantity': '实际数量',
            'note': '备注',
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(InventoryForm, self).__init__(*args, **kwargs)
        # 显示所有商品
        self.fields['goods'].queryset = Goods.objects.all()

    def clean(self):
        cleaned_data = super().clean()
        goods = cleaned_data.get('goods')
        location = cleaned_data.get('location')
        batch_number = cleaned_data.get('batch_number')
        actual_quantity = cleaned_data.get('actual_quantity')

        if goods and location and batch_number:
            # 获取系统中的库存数量
            try:
                stock = Stock.objects.get(
                    goods=goods,
                    location=location,
                    batch_number=batch_number
                )
                cleaned_data['system_quantity'] = stock.quantity
            except Stock.DoesNotExist:
                cleaned_data['system_quantity'] = 0

            # 计算差异数量
            if actual_quantity is not None:
                cleaned_data['difference'] = actual_quantity - cleaned_data['system_quantity']

        return cleaned_data

    def save(self, commit=True):
        inventory = super(InventoryForm, self).save(commit=False)
        if self.user:
            inventory.operator = self.user
        
        # 如果还没有设置系统数量，则从Stock中获取
        if not inventory.system_quantity:
            try:
                stock = Stock.objects.get(
                    goods=inventory.goods,
                    location=inventory.location,
                    batch_number=inventory.batch_number
                )
                inventory.system_quantity = stock.quantity
            except Stock.DoesNotExist:
                inventory.system_quantity = 0
        
        # 计算差异数量
        inventory.difference = inventory.actual_quantity - inventory.system_quantity
        
        if commit:
            inventory.save()
            
            # 更新库存记录
            stock, created = Stock.objects.get_or_create(
                goods=inventory.goods,
                location=inventory.location,
                batch_number=inventory.batch_number,
                defaults={'quantity': inventory.actual_quantity}
            )
            if not created:
                stock.quantity = inventory.actual_quantity
                stock.save()
                
        return inventory


class WageCalculationForm(forms.Form):
    start_date = forms.DateField(
        label='开始日期',
        widget=forms.DateInput(attrs={'class': 'form-control', 'type': 'date'})
    )
    end_date = forms.DateField(
        label='结束日期',
        widget=forms.DateInput(attrs={'class': 'form-control', 'type': 'date'})
    )
    
    def clean(self):
        cleaned_data = super().clean()
        start_date = cleaned_data.get('start_date')
        end_date = cleaned_data.get('end_date')
        
        if start_date and end_date and start_date > end_date:
            raise forms.ValidationError('开始日期不能晚于结束日期')
        
        return cleaned_data